package com.firesrc.web;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jodd.datetime.JDateTime;
import jodd.db.DbThreadSession;
import jodd.db.oom.sqlgen.DbEntitySql;
import jodd.util.StringUtil;

import com.firesrc.bean.Keyword;
import com.firesrc.bean.Record;
import com.firesrc.service.ScheduleExecutorManagerFactory;
import com.firesrc.service.SuperScheduledExecutorManager;
import com.firesrc.util.IU;
import com.firesrc.util.SystemUtil;

/**
 * Servlet implementation class ImportKeyword
 */
public class ImportKeyword extends SuperServlet {
  private static final long serialVersionUID = 1L;

  /**
   * @see HttpServlet#HttpServlet()
   */
  public ImportKeyword() {
    super();
    // TODO Auto-generated constructor stub
  }

  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
  }

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    response.setCharacterEncoding("GBK");
    response.setContentType("text/html; charset=gb2312");
    String keyword = request.getParameter("keyword");
    String mails = request.getParameter("mails");
    String topic = request.getParameter("topic");
    String count = request.getParameter("count");
    int countInt = Integer.parseInt(count);
    if (StringUtil.isBlank(keyword)) {
      response.getWriter().println("关键字不能为空");
      return;
    }

    DbThreadSession dbThreadSession = new DbThreadSession(cp);
    boolean isImportNewKewword = StringUtil.isBlank(mails) && !StringUtil.isBlank(keyword);
    if (isImportNewKewword) {
      String date = "";
      if (StringUtil.isBlank(topic)) {
        date = new JDateTime().toString("YYYY-MM-DD-hhmm");
      }

      keyword = StringUtil.replace(keyword, "，", ",");
      String[] keywordArray = keyword.split(",");
      Keyword keywordIn = null;
      for (String string : keywordArray) {
        keywordIn = new Keyword();
        if (StringUtil.isBlank(topic)) {
          keywordIn.setId(IU.g());
          keywordIn.setName(string);
          keywordIn.setTopic("无主题" + date);
        } else {
          keywordIn.setId(IU.g());
          keywordIn.setName(string + topic);
          keywordIn.setTopic(topic);
        }
        keywordIn.setState("0");
        keywordIn.setFlag('d');
        keywordIn.setCreatedate(SystemUtil.getCurrentDateYYYYMMDD());
        keywordIn.setSearchcount(countInt);
        try {
          DbEntitySql.insert(keywordIn).query().executeUpdateAndClose();
        } catch (Exception e) {
          // TODO Auto-generated catch block
          System.out.println("输入的关键字有重复,或者长度太长" + e.getMessage());
        }
      }
      response.getWriter().println("插入关键词成功! 共" + keywordArray.length + "条");
      SuperScheduledExecutorManager searchMailExecutorManager = ScheduleExecutorManagerFactory.getSearchMailExecutorManager();
      if (searchMailExecutorManager.isShutdown()) {
        searchMailExecutorManager.start();
      }

      return;
    }

    String[] split = mails.split(",");
    new DbThreadSession(cp);
    Record record;
    int repeat = 0;
    int insert = 0;
    for (String string : split) {
      if (StringUtil.isNotEmpty(string)) {
        if (cache.get(string) != null) {
          System.out.println("邮箱<" + string + ">已经存在!");
          repeat++;
        } else {
          record = new Record();
          record.setId(UUID.randomUUID().toString());
          record.setKeyword(keyword);
          record.setMail(string);
          record.setTopic(topic);
          DbEntitySql.insert(record).query().executeUpdateAndClose();
          cache.put(string, record);
          System.out.println("导入邮箱:" + string);
          insert++;
        }
      }
      ;
    }

    Keyword keyword1 = new Keyword();
    keyword1.setId(IU.g());
    keyword1.setName(keyword);
    keyword1.setState("1");
    keyword1.setTopic(topic);
    keyword1.setCreatedate(SystemUtil.getCurrentDateYYYYMMDD());
    try {
      DbEntitySql.insert(keyword).query().executeUpdateAndClose();
    } catch (Exception e) {
      // TODO Auto-generated catch block
      System.err.println("错误信息是:--" + e.getMessage());
    }
    dbThreadSession.closeSession();
    response.getWriter().println("导入关键字<" + keyword + "> " + insert + "条,已经重复的关键字有" + repeat + "条");
  }
}
